package svc

import (
	"gitee.com/gopher2011/datacenter/internal/config"
	"gitee.com/gopher2011/datacenter/internal/middleware"
	_ "github.com/go-sql-driver/mysql"
	"github.com/kotlin2018/mbt"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/tal-tech/go-zero/core/stores/cache"
	"github.com/tal-tech/go-zero/core/syncx"
	"github.com/tal-tech/go-zero/rest"
	"io"
	"path"
	"time"
)

type ServiceContext struct {
	Config    config.Config
	Cache     cache.Cache
	Usercheck rest.Middleware
}

func NewServiceContext(c config.Config) *ServiceContext {
	conf := &mbt.Database{
		Pkg:        c.Database.Pkg,
		DriverName: c.Database.DriverName,
		DSN:        c.Database.DSN,
		Logger: &mbt.Logger{
			Path:     c.Logger.Path,
			MaxAge:   c.Logger.MaxAge,
			Interval: c.Logger.Interval,
			PrintSql: true,
		},
	}
	mbt.New(conf).SetOutPut(initLogger(c.Logger.Path, c.Logger.MaxAge, c.Logger.Interval))
	return &ServiceContext{
		Config:    c,
		Cache:     cache.New(c.CacheRedis, syncx.NewSharedCalls(), cache.NewStat(""), nil),
		Usercheck: middleware.NewUsercheckMiddleware().Handle,
	}
}

func initLogger(logFilePath string, maxAge, interval int) io.Writer {
	writer, _ := rotatelogs.New(
		path.Join(logFilePath+"-%Y-%m-%d.log"), //拼接成log文件名
		rotatelogs.WithLinkName(logFilePath),
		rotatelogs.WithMaxAge(time.Duration(maxAge)*time.Minute),
		rotatelogs.WithRotationTime(time.Duration(interval)*time.Minute),
	)
	return writer
}
